// analyzeFormat.js
const fs = require('fs');
const path = require('path');

const { getAllFilesInDirectory } = require('../../../utils/fileUtils');

class FormatParser {
    async parse(dataset_info) {
        // console.log('vision detection format parser!');
        const dataset_dir = dataset_info.dataset_dir;

        // 判断是否是coco格式标注，并返回所有符合coco格式标注的文件内容
        let jsonFiles = await getAllFilesInDirectory(dataset_info.dataset_dir, ['.json'], ['workspace']);
        let cocoFiles = [];
        for (let i = 0; i < jsonFiles.length; i++) {
            const relativePath = path.relative(dataset_dir, jsonFiles[i]);
            cocoFiles.push(relativePath);
        }
        if (cocoFiles.length > 0) {
            return { code: 0, msg: { formats: ['coco'], format: 'coco', labels: cocoFiles } };
        }

        return { code: 0, msg: { formats: ['coco'], format: 'coco', labels: [] } };
    }

    isCOCOFormat(jsonPath) {
        // 读取jsonFile
        const jsonData = fs.readFileSync(jsonPath, 'utf8');
        const cocoJson = JSON.parse(jsonData);

        // 检查JSON文件是否符合COCO格式
        if (!cocoJson.images || !cocoJson.annotations || !cocoJson.categories) {
            return false;
        } else {
            return true;
        }
    }
}

module.exports = FormatParser;
